﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Serveur.DataAccess.EF;
using AutoMapper;

namespace Serveur.DataAccess
{
    /// <summary>
    /// Handles EF context instantiation and containment. The context is renewed every few
    /// minutes to ensure it does not grow too big in memory while providing some caching.
    /// </summary>
    public class ContextHandler
    {
        /// <summary>
        /// Gets an auto-managed context for EF interractions. This context is renewed every few minutes
        /// as compromise between cache and memory siez.
        /// </summary>
        public static GameEntitiesContainer Context
        {
            get
            {
                if (_context == null ||
                    DateTime.Now.Ticks - _lastCreated > (long) 60 * 1000 * 10000) // 1 minute.
                {
                    if (_context == null)
                    {
                        // Setting the mapper.
                        Mapper.CreateMap<EF.UnitStatistics, DBO.UnitStatistics>();
                        Mapper.CreateMap<EF.Resources, DBO.Economy.Resources>();
                        Mapper.CreateMap<EF.Race, DBO.Race>();
                        Mapper.CreateMap<EF.UnitSlot, DBO.UnitSlot>();
                        Mapper.CreateMap<EF.UnitType, DBO.UnitType>();
                        Mapper.CreateMap<EF.SquadSlot, DBO.Army.SquadSlot>().
                            ForMember(x => x.TroopType, o => o.MapFrom(src => src.Unit.Name));
                        Mapper.CreateMap<EF.Squad, DBO.Army.Squad>();
                    }
                    else
                        _context.Dispose();
                    _context = new GameEntitiesContainer();
                    _lastCreated = DateTime.Now.Ticks;
                }
                return _context;
            }
        }

        private static GameEntitiesContainer _context;
        private static long _lastCreated;
    }
}
